package com.atguigu.tingshu.account.service.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.account.mapper.UserAccountDetailMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.atguigu.tingshu.vo.account.AccountDeductVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Map;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    @Autowired
    private UserAccountMapper userAccountMapper;

    @Autowired
    private UserAccountDetailMapper userAccountDetailMapper;

    /**
     * 保存账户记录
     *
     * @param map
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserAccount(Map<String, Object> map) {
        //1.新增账户记录
        Long userId = (Long) map.get("userId");
        BigDecimal amount = (BigDecimal) map.get("amount");
        UserAccount userAccount = new UserAccount();
        userAccount.setUserId(userId);
        userAccount.setTotalAmount(amount);
        userAccount.setLockAmount(BigDecimal.ZERO);
        userAccount.setAvailableAmount(amount);
        userAccount.setTotalIncomeAmount(amount);
        userAccount.setTotalPayAmount(BigDecimal.ZERO);
        int rows = userAccountMapper.insert(userAccount);
        if (rows > 0) {
            String title = (String) map.get("title");
            String orderNo = (String) map.get("orderNo");
            //2.保存账户变动日志
            this.saveUserAccountDetail(userId, title, SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT, amount, orderNo);
        }

    }

    /**
     * 保存账户变动日志（例如：充值，消费）
     *
     * @param userId  用户ID
     * @param title   内容
     * @param amount  金额
     * @param orderNo 订单编号
     */
    @Override
    public void saveUserAccountDetail(Long userId, String title, String tradeType, BigDecimal amount, String orderNo) {
        UserAccountDetail userAccountDetail = new UserAccountDetail();
        userAccountDetail.setUserId(userId);
        userAccountDetail.setTitle(title);
        userAccountDetail.setTradeType(tradeType);
        userAccountDetail.setAmount(amount);
        userAccountDetail.setOrderNo(orderNo);
        userAccountDetailMapper.insert(userAccountDetail);
    }

    /**
     * 获取指定用户账户可用金额
     *
     * @param userId
     * @return
     */
    @Override
    public BigDecimal getAvailableAmount(Long userId) {
        UserAccount userAccount = userAccountMapper.selectOne(
                new LambdaQueryWrapper<UserAccount>()
                        .eq(UserAccount::getUserId, userId)
        );
        Assert.notNull(userAccount, "用户账户不存在！");
        return userAccount.getAvailableAmount();
    }

    /**
     * 检查扣减账户余额
     *
     * @param accountDeductVo
     */
    @Override
    public void checkAndDeduct(AccountDeductVo accountDeductVo) {
        //1.检查余额是否满足扣减条件，采用数据库"锁机制"悲观锁，解决并发问题
        UserAccount userAccount = userAccountMapper.checkDeduction(accountDeductVo.getUserId(), accountDeductVo.getAmount());
        if (userAccount == null) {
            throw new RuntimeException("账户余额不足！");
        }
        //2.如果满足扣减条件，扣减账户余额
        int rows = userAccountMapper.update(null,
                new LambdaUpdateWrapper<UserAccount>()
                        .eq(UserAccount::getUserId, accountDeductVo.getUserId())
                        .setSql("total_amount = total_amount - " + accountDeductVo.getAmount())
                        .setSql("available_amount = available_amount - " + accountDeductVo.getAmount())
                        .setSql("total_pay_amount = total_pay_amount + " + accountDeductVo.getAmount())
        );
        if (rows == 0) {
            throw new RuntimeException("账户余额不足！");
        }
        //3.保存账户变动日志
        this.saveUserAccountDetail(accountDeductVo.getUserId(), accountDeductVo.getContent(), SystemConstant.ACCOUNT_TRADE_TYPE_MINUS, accountDeductVo.getAmount(), accountDeductVo.getOrderNo());
    }
}
